package com.rico.redis.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisService {
    @Autowired
    private RedisTemplate redisTemplate;

    public String getCache(String key) {
        return (String)redisTemplate.opsForValue().get(key);
    }

    public void setCache(String key, String value) {
        redisTemplate.opsForValue().set(key,value);
    }
    
    /**
     * 分布式锁
     * @param lockId key
     * @param value value
     * @param millisecond 秒
     * @return
     */
    public boolean getLock(String lockId,String value, long millisecond) {
    	 Boolean success = redisTemplate.opsForValue().setIfAbsent(lockId, value,millisecond, TimeUnit.MILLISECONDS);
    	 return success != null && success;
    }
    /**
     * 释放销
     * @param lockId
     */
    public void releaseLock(String lockId) {
    	 redisTemplate.delete(lockId);
    }
}




